package com.mrx.test.junit;


import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ReferenceConfig;
import org.apache.dubbo.config.RegistryConfig;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class DubboUtils {

    private static final Map<String, Object> serviceMap = new HashMap<>();

    @SuppressWarnings("unchecked")
    public static <T> T getService(Class<T> clazz) {
        String key = clazz.getName();
        Object objService = serviceMap.get(key);
        if (serviceMap.containsKey(key)) {
            return (T) objService;
        }
        ReferenceConfig<T> reference = createReferenceConfig();
        // 弱类型接口名
        reference.setInterface(clazz);
        // 声明为泛化接口
        reference.setGeneric("false");
        objService = reference.get();
        serviceMap.put(key, objService);
        return (T) objService;
    }

    @SuppressWarnings("deprecation")
    private static <T> ReferenceConfig<T> createReferenceConfig() {
        // 普通编码配置方式
        ApplicationConfig application = new ApplicationConfig();
        // 客户端应用名：可以任意取名
        application.setName("dubbo-test-application");
        application.setLogger("slf4j");
        // 连接注册中心配置
        RegistryConfig registry = new RegistryConfig();
        registry.setAddress(getConfig("dubbo.registry.address"));
        // 引用远程服务
        // 该实例很重量，里面封装了所有与注册中心及服务提供方连接，请缓存
        ReferenceConfig<T> reference = new ReferenceConfig<>();
        reference.setApplication(application);
        reference.setRegistries(Collections.singletonList(registry));
        reference.setCheck(false);
        return reference;
    }

    @SuppressWarnings({"unchecked", "SameParameterValue"})
    private static <T> T getConfig(String key) {
        // InputStream inputStream = DubboUtils.class.getResourceAsStream("/application-dubbo.yml");
        // return (T) new Yaml().loadAs(inputStream, JSONObject.class).getByPath(key);
        // TODO: 2023-04-08 上午 9:27:24 动态读取配置
        return (T) "nacos://localhost:8848";
    }

}
